<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.id">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="val in item.values" :key="val.name">
          <img @click="changeSku(item, val)" :class="{ selected: val.selected, disabled: val.disabled }"
            v-if="val.picture" :src="val.picture" :title="val.name" />
          <span v-else @click="changeSku(item, val)" :class="{ selected: val.selected, disabled: val.disabled }">{{
          val.name }}</span>
        </template>
      </dd>
    </dl>
  </div>
</template>
<script>
import powerSet from '@/vender/power'

export default {
  name: 'GoodsSku',
  props: {
    goods: {
      type: Object,
      default: () => ({})
    },
    skuId: {
      type: String,
      default: ''
    }
  },

  setup (props, context) {
    // 获取所有笛卡尔积结果
    const pathMap = getPathMap(props.goods.skus)

    // 第一次更新
    updateDisabledStatus(props.goods.specs, pathMap)

    // 初始化默认选择
    initDefaultSelected(props.goods, props.skuId)

    // 选中或取消选中
    function changeSku (item, val) {
      if (val.disabled) {
        return false
      }
      if (val.selected) {
        val.selected = false
      }
      item.values.forEach(valItem => {
        valItem.selected = false
      })
      val.selected = true
      // 重新更新
      updateDisabledStatus(props.goods.specs, pathMap)
      // 选择的规格属性
      const selectedArr = getSelectedValues(props.goods.specs).filter(v => v)
      // 判断是否全选中
      if (selectedArr.length === props.goods.specs.length) {
        const skuIds = pathMap[selectedArr.join(spliter)]
        const sku = props.goods.skus.find(sku => sku.id === skuIds[0])
        // 传递
        context.emit('change', {
          skuId: sku.id,
          price: sku.price,
          oldPrice: sku.oldPrice,
          inventory: sku.inventory,
          specsText: sku.specs.reduce((p, n) => `${p} ${n.name}：${n.valueName}`, '').trim()
        })
      } else {
        context.emit('change', {})
      }
    }

    return {
      changeSku
    }
  }
}

// 默认选择
const initDefaultSelected = (goods, skuId) => {
  // 1.找出sku信息
  const sku = goods.skus.find(item => item.id === skuId)
  if (goods.specs && sku) {
    // 2.遍历每一个按钮
    goods.specs.forEach((item, i) => {
      const val = item.values.find(val => val.name === sku.specs[i].valueName)
      val.selected = true
    })
  }
}

const spliter = '★'
// 得到一个路径字典对象
const getPathMap = (skus) => {
  const pathMap = {}
  // 筛选出有效的sku
  skus.forEach(sku => {
    if (sku.inventory > 0) {
      const valueArr = sku.specs.map(val => val.valueName)
      // 计算sku子集
      // powerSet()
      const valueArrPowerSet = powerSet(valueArr)
      valueArrPowerSet.forEach(arr => {
        const key = arr.join(spliter)
        // 给字典添加东西
        if (pathMap[key]) {
          pathMap[key].push(sku.id)
        } else {
          pathMap[key] = [sku.id]
        }
      })
    }
  })
  return pathMap
}

// 更新按钮禁用状态
const updateDisabledStatus = (specs, pathMap) => {
  specs.forEach((item, i) => {
    const selectedValues = getSelectedValues(specs)
    item.values.forEach(val => {
      // 已经被选择，直接返回
      if (val.selected) {
        return
      }
      selectedValues[i] = val.name
      const key = selectedValues.filter(val => val).join(spliter)
      //  不在笛卡尔积中的设置为禁用
      val.disabled = !pathMap[key]
    })
  })
}

// 选择值数组
const getSelectedValues = (specs) => {
  const arr = []
  specs.forEach(item => {
    // 选择出被选中的
    const selectVal = item.values.find(val => val.selected)
    arr.push(selectVal ? selectVal.name : undefined)
  })
  return arr
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;

  &.selected {
    border-color: @xtxColor;
  }

  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}

.goods-sku {
  padding-left: 10px;
  padding-top: 20px;

  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;

    dt {
      width: 50px;
      color: #999;
    }

    dd {
      flex: 1;
      color: #666;

      >img {
        width: 50px;
        height: 50px;
        .sku-state-mixin ();
      }

      >span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        margin-bottom: 3px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>
